<script lang="ts" setup>
import type { FetchAddressListRes } from '@/types/api/other'
import { otherApi } from '@/request/api'
import { useGetLocation, useHideLoading, useLoading, useModal, useNav, useNavBack, useRouteGuard } from '@/utils'
import { onLoad } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { isEmpty } from 'lodash-es'
import { reactive, ref } from 'vue'
import { enum as zenum, object as zobject, string as zstring } from 'zod'

const list = ref<FetchAddressListRes['data']>([])
const from = ref<'checkout'>()
const load = reactive({
  once: false,
})

onLoad(async (query) => {
  const zparse = zobject({
    from: zenum(['checkout']).optional(),
  }).safeParse(query)
  if (!zparse.success) {
    return await useRouteGuard()
  }

  if ('from' in zparse.data) {
    from.value = zparse.data.from
  }

  await getAddressList()
})

async function getAddressList() {
  load.once = false
  useLoading(true)
  const [err, res] = await to(otherApi.fetchAddress({ pageSize: 50 }))
  load.once = true
  useHideLoading()
  if (err) {
    return
  }
  list.value = res.data
}

async function handleClickItemText(item: FetchAddressListRes['data'][0]) {
  if (from.value === 'checkout') {
    const zparse = zobject({
      province: zstring().min(1),
      city: zstring().min(1),
      district: zstring().min(1),
      address: zstring().min(1),
      tit: zstring().min(1),
      phone: zstring().min(1),
    }).safeParse(item)
    if (!zparse.success) {
      const { confirm } = await useModal({
        title: '温馨提示',
        content: '该地址内容或格式有误，请重新编辑',
        cancelText: '取消',
        confirmText: '编辑',
      })
      if (confirm) {
        useNav('/me/address/item', { id: item.id })
      }
      return
    }

    // #ifdef MP-ALIPAY
    const [err, res] = await to(useGetLocation())
    if (err) {
      return
    }
    uni.$emit('updateCheckoutAddress', {
      address: item,
      location: res,
    })
    useNavBack()
    // #endif

    // #ifdef H5 || MP-WEIXIN || MP-KUAISHOU
    uni.$emit('updateCheckoutAddress', { address: item })
    useNavBack()
    // #endif
  }
  else {
    uni.$once('refreshAddressList', getAddressList)
    useNav('/me/address/item', { id: item.id })
  }
}

function handleClickItemArrow(item: FetchAddressListRes['data'][0]) {
  uni.$once('refreshAddressList', getAddressList)
  useNav('/me/address/item', { id: item.id })
}

function handleNavNew() {
  uni.$once('refreshAddressList', getAddressList)
  useNav('/me/address/item')
}
</script>

<template>
  <template v-if="load.once">
    <view v-if="!isEmpty(list)" class="px-30px pt-20px">
      <template v-for="(item, i) in list" :key="item.id">
        <!--  -->
        <view class="flex items-stretch rd-16px bg-white" :class="{ 'mt-10px': i !== 0 }">
          <view class="flex flex-1 flex-col py-30px pl-30px text-26px" @click="handleClickItemText(item)">
            <view class="text-#3 routine-lh">{{ item.province || '?' }}{{ item.city || '?' }}{{ item.district || '?' }}{{ item.address || '?' }}</view>
            <view class="mt-10px flex items-center">
              <view class="text-#6">{{ item.tit || '?' }} {{ item.phone || '?' }}</view>
            <!-- <template v-if="item.defaultValue === 1">
                <view class="text-theme-oragne ml-10px b-2px b-theme-primary rd-6px b-solid bg-theme-primary/10 px-10px text-18px text-theme-primary lh-30px">默认</view>
              </template> -->
            </view>
          </view>
          <view class="flex items-center px-30px" @click="handleClickItemArrow(item)">
            <view v-if="from === 'checkout'" class="i-ri:edit-2-line text-34px text-#6"></view>
            <view v-else class="i-ri:arrow-right-wide-line text-34px text-#6"></view>
          </view>
        </view>
      </template>

      <view class="safe-pb-15px">
        <view class="h-115px"></view>
      </view>
    </view>
    <view v-else class="flex flex-col items-center pb-100px pt-200px">
      <view class="i-icon-park-outline:map-draw text-100px text-gray-300"></view>
      <view class="mt-20px text-gray-600">没有地址，请先添加</view>
    </view>
  </template>

  <view class="fixed bottom-0 w-full flex bg-white pt-15px safe-pb-15px">
    <view class="btn-primary-black mx-a w-600px text-36px lh-80px" @click="handleNavNew">新增地址</view>
  </view>
</template>

<style lang="less" scoped></style>
